import React, { useEffect } from 'react'
import './index.less'
import { useState } from '../hooks/useHooks'

const RequestIdleCallbackDemo = () => {
	let iniTask1 = [
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第一个任务')
			document.getElementById('test').innerHTML = 1
		},
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第二个任务')
			document.getElementById('test').innerHTML = 2
		},
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第三个任务')
			document.getElementById('test').innerHTML = 3
		},
	]
	let iniTask2 = [
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第一个任务')
			document.getElementById('test').innerHTML = 1
		},
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第二个任务')
			document.getElementById('test').innerHTML = 2
		},
		function () {
			for (let i = 0; i < 5000; i++) {
				// console.log(i)
			}
			console.log('第三个任务')
			document.getElementById('test').innerHTML = 3
		},
	]
	let task1 = [...iniTask1]
	let task2 = [...iniTask2]

	useEffect(() => {
        const timer = setInterval(() => {
            document.getElementById('ui').innerHTML = parseInt(document.getElementById('ui').innerHTML) + 1
        }, 100)

		return () => {
        	clearInterval(timer)
		}
	}, [])


	//执行myTest文件会影响上面动态dom的渲染
	const myTest = () => {
		if (task1.length > 0) {
			work1(task1)
		}
	}

	//将js计算任务放在requestIdleCallback中运算
	const startRequestIdleCallback = () => {
		window.requestIdleCallback(myNonEssentialWork, { timeout: 200 })
		// window.requestIdleCallback(myNonEssentialWork, { timeout: 2000 });
	}

	function myNonEssentialWork(deadline) {
		//alert(deadline.timeRemaining())
		console.log(deadline, 'deadline')
		console.log(deadline.timeRemaining(), 'deadline.timeRemaining()')
		// 如果帧内有富余的时间，或者超时
		while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && task2.length > 0) {
			work2(task2)
		}
		//开启下一个空闲时间的回调函数
		if (task2.length > 0) {
			window.requestIdleCallback(myNonEssentialWork)
		}
		if (task2.length === 0) {
			task2 = [...iniTask2]
		}
	}

	function work1(tasks) {
		tasks.shift()()
		console.log('任务执行完成')
		if (task1.length > 0) {
			work1(task1)
		}
	}

	function work2(tasks) {
		tasks.shift()()
		console.log('任务执行完成')
	}

	return (
		<div>
			<div id="ui">0</div>
			<div>
				执行<span id="test">0</span>
			</div>
			<button onClick={myTest}>常规执行计算任务</button>
			<button onClick={startRequestIdleCallback}>在requestIdleCallback中执行计算任务</button>
		</div>
	)
}

export default RequestIdleCallbackDemo
